<template>
  <div class="search-panel-customer">
    <base-panel :show.sync="visible" :width="panelWidth">
      <h3 slot="title">
        <span>高级搜索</span>
        <el-dropdown class="pull-right" trigger="click" @command="setAdvanceSearchColumn">
          <i class="iconfont icon-xitongguanli customer-panel-btn" style="float: none;"></i>

          <el-dropdown-menu slot="dropdown" class="customer-advance-setting">
            <el-dropdown-item command="1">一栏</el-dropdown-item>
            <el-dropdown-item command="2">两栏</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </h3>
      <el-form label-position="top" class="advanced-search-form" onsubmit="return false;">
        <search-form 
          :fields="fields" 
          ref="searchForm" 
          :form-backup="formBackup" 
          :column-num="columnNum" 
          :synergiesUserOptions="synergiesUserOptions"
        >
        </search-form>
        <slot name="footer"></slot>
      </el-form>
    </base-panel>

    <!-- 遮罩层 -->
    <div v-if="visible" class="cover"></div>
  </div>
</template>

<script>
import { FormFieldMap, SettingComponents } from '@src/component/form/components';
import * as Utils from '@src/component/form/util';
import { formatDate } from 'pub-bbx-utils';
import { isEmptyStringObject } from '@src/util/function';

import { formatAddress } from 'pub-bbx-utils';
import { baseDistValueToObject } from '@src/util/addressUtil'
export default {
  name: 'search-panel',
  props: {
    config: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      visible: false,
      formBackup: {},
      columnNum: 1,
      synergiesUserOptions: {
        backUp: new Map(),
        init: []
      },
    }
  },
  computed: {
    fields() {
      return this.config.fields;
    },
    panelWidth() {
      return `${420 * this.columnNum}px`;
    },
  },
  mounted() {
    const {column_number} = this.getLocalStorageData();
    if(column_number) this.columnNum = Number(column_number)
  },
  methods: {
    saveDataToStorage(key, value) {
      const data = this.getLocalStorageData();
      data[key] = value;
      localStorage.setItem('product_list_localStorage_19_4_24', JSON.stringify(data));
    },
    getLocalStorageData() {
      const dataStr = localStorage.getItem('product_list_localStorage_19_4_24') || '{}';
      return JSON.parse(dataStr);
    },
    resetParams() {
      this.formBackup = {};
      this.$refs.searchForm && this.$nextTick(this.$refs.searchForm.initFormVal)
    },

    buildParams(formData) {
      const form = formData || this.$refs.searchForm.returnData();
      this.formBackup = Object.assign({}, form);

      const isSystemFields = this.fields.filter(f => f.isSystem);
      const notSystemFields = this.fields.filter(f => !f.isSystem);
      let params = {
        conditions: [],
      };

      let tv = null;
      let fn = '';

      for(let i = 0;i < isSystemFields.length;i++) {
        tv = isSystemFields[i];
        fn = tv.fieldName;

        if (fn === 'synergies' && form[fn]) {
          params.synergyUserIds = form[fn]
          continue;
        }

        // hasRemind
        if ((fn === 'hasRemind' || fn === 'status') && form[fn] !== '') {
          params[fn] = form[fn];
          continue;
        }

        if (!form[fn] || (Array.isArray(form[fn]) && !form[fn].length)) {
          continue;
        }

        if (fn === 'area') {
          // 国际化地址组件返回的第一个是国家，非国际化组件第一个返回的是省
          let {country, province, city, dist} = baseDistValueToObject(form[fn]);
          params.customerAddress = {
            ...params.customerAddress || {},
            adProvince: province,
            adCity: city,
            adDist: dist
          }
          country && (params.customerAddress.adCountry = country);
          continue;
        }

        if (fn === 'addressDetail') {
          params.customerAddress = {
            ...params.customerAddress || {},
            adAddress: form[fn]
          }
          continue;
        }

        if (['date', 'datetime'].includes(tv.formType)) {
          params[`${fn}Start`] = form[fn][0];
          params[`${fn}End`] = form[fn][1];
          continue;
        }

        if (tv.formType === 'tags') {
          params.tagId = form[fn].map(({id}) => id).join('');
        }

        if (typeof form[fn] === 'string') {
          params[fn === 'customer' ? 'customerId' : fn] = form[fn];
          continue;
        }
      }

      for(let i = 0;i < notSystemFields.length;i++) {
        let key = null;
        tv = notSystemFields[i];
        fn = tv.fieldName;

        if (!form[fn] || (Array.isArray(form[fn]) && !form[fn].length)) {
          continue;
        }

        // 空对象
        if (typeof form[fn] === 'object' && !Array.isArray(form[fn]) && !Object.keys(form[fn]).length) {
          continue;
        }

        if (['date', 'datetime'].includes(tv.originalFormType)) {
          params.conditions.push({
            property: fn,
            operator: tv.operator,
            betweenValue1: form[fn][0],
            betweenValue2: form[fn][1],
          });
          continue;
        }

        if (['related_customers', 'cascader'].includes(tv.formType)) {
          params.conditions.push({
            property: fn,
            operator: tv.operator,
            inValue: form[fn]
          });
          continue;
        }

        if (tv.formType === 'address') {
          let address = {
            property: fn,
            operator: tv.operator,
          };
          let isEmpty = isEmptyStringObject(form[fn]);

          if(!isEmpty) {
            address.value = formatAddress(form[fn],'');
            params.conditions.push(address);
          }
          continue;
        }

        if (tv.originalFormType === 'related_task') {
          key = "taskNo";
        }

        params.conditions.push({
          property: fn,
          operator: tv.operator,
          value: form[fn],
          key
        });
      }

      return params;
    },
    setAdvanceSearchColumn(command) {
      this.columnNum = Number(command);
      this.saveDataToStorage('column_number', command);
    },
    open() {
      this.visible = true;
      this.synergiesUserOptions.init = [...this.synergiesUserOptions.backUp.values()]
    }
  },
  components: {
    SearchForm: {
      name: 'search-form',
      props: {
        fields: {
          type: Array,
          default: () => ([])
        },
        formBackup: {
          type: Object,
          default: () => ({})
        },
        columnNum: {
          type: Number,
          default: 1
        },
        synergiesUserOptions: {
          type: Object
        }
      },
      data() {
        return {
          form: {},
          tableName: 'product',
        }
      },
      mounted() {
        this.buildForm();
      },
      methods: {
        returnData() {
          return Object.assign({}, this.form);
        },
        buildForm() {
          if (Object.keys(this.form).length === this.fields.length) return;
          this.initFormVal();
        },
        initFormVal() {
          let fields = this.fields;
          let form = {};
          let tv = '';

          fields.forEach(field => {
            tv = '';
            // 地址的默认值初始化为对象
            if(field.formType == 'customerAddress' || field.formType == 'address') tv = {};
            if(field.formType == 'date' || field.formType == 'datetime') tv = [];
            if (field.formType === 'link') {
              tv = {}
            }
            if(['tags', 'area', 'cascader', 'related_customers'].includes(field.formType)) {
              tv = []
            }
            if (field.formType === 'select' && (field.displayName === '服务团队' || field.displayName === '服务部门')) {
              tv = []
            }
            form[field.fieldName] = this.formBackup[field.fieldName] || tv;


            if (field.fieldName === 'status' || field.fieldName === 'hasRemind') {
              this.$set(this.form, field.fieldName, Number(this.formBackup[field.fieldName]) >= 0 ? this.formBackup[field.fieldName] : '')
            } else {
              this.$set(this.form, field.fieldName, this.formBackup[field.fieldName] || tv)
            }
          });

          return form;
        },
        update(event, action) {
          if (action === 'tags') {
            return this.$set(this.form,'tags',event);
          }

          if (action === 'dist') {
            return this.$set(this.form,'area',event);
          }
          const f = event.field;
          this.$set(this.form,f.fieldName,event.newValue);

        },
        renderInput(h, field) {
          const f = {
            ...Object.freeze(field),
          }

          let comp = FormFieldMap.get(f.formType);

          if (!comp && f.formType !== 'tags' && f.formType !== 'area' && f.formType !== 'linkman') {
            return null;
          }

          if (f.formType === 'select') {
            f.setting.isMulti = false;
          }

          let childComp = null;

          if (f.formType === 'tags') {

            childComp = h(
              'biz-team-select',
              {
                props: {
                  value: this.form[f.fieldName],
                },
                on: {
                  input: event => this.update(event, 'tags')
                }
              }
            )
          } else if (f.formType === 'area') {
            childComp = h(
              'base-dist-picker',
              {
                props: {
                  value: this.form[f.fieldName],
                },
                on: {
                  input: event => this.update(event, 'dist')
                }
              });
          } else if (f.formType === 'linkman') {
            childComp = h(
              'linkman-search',
              {
                props: {
                  field: f,
                  value: this.form[f.fieldName],
                  disableMap: true,
                },
                on: {
                  update: event => this.update(event)
                }
              });
          } else if (f.formType === 'related_customers') {
            childComp = h("customer-search", {
              props: {
                field: f,
                value: this.form[f.fieldName],
                disableMap: true,
                multiple: true
              },
              on: {
                update: (event) => this.update(event),
              },
            });
          } else {
            let userList
            // 选项变更后，关闭高级搜索再打开，会导致名称不显示
            if (f.fieldName === 'synergies' && this.synergiesUserOptions.init.length) {
              userList = this.synergiesUserOptions.init
            }
            childComp = h(
              comp.extend && comp.extend[`${f.formType}_search`]
                ? comp.extend[`${f.formType}_search`]
                : comp.build,
              {
                props: {
                  field: f,
                  value: this.form[f.fieldName],
                  disableMap: true,
                  placeholder: Utils.genPlaceholder(f),
                  multiple: f.fieldName === 'synergies' ? true : void 0,
                  userList
                },
                on: {
                  // update: event => this.update(event)
                  update: (event) => {
                    if (f.fieldName === 'synergies') {
                      let synergiesUserOptions = new Map(event.newValue.map(v => {
                        let option = event.options.find(option => option.id === v) || this.synergiesUserOptions.backUp.get(v)
                        return [v, option]
                      }))
                      this.synergiesUserOptions.backUp = synergiesUserOptions
                    }
                    this.update(event)
                  },
                }
              });
          }

          return h(
            'form-item',
            {
              props: {
                label: f.displayName,
                needValidate: false,
              }
            },
            [childComp]
          )
        }
      },
      render(h) {
        return (
          <div class={`form-item-container ${this.columnNum == 2 ? 'two-columns' : ''}`}>
            {this.fields.map(f => this.renderInput(h, f))}
          </div>
        )
      },
      components: {...SettingComponents}
    }
  }
}
</script>

<style lang="scss">
  .advanced-search-form {
    overflow: auto;
    padding: 10px 15px 63px 15px;

    height: calc(100% - 52px);
    justify-content: space-between;

    .two-columns {
      display: flex;
      flex-wrap: wrap;
      .el-form-item {
        width: 50%;
      }
    }

    .form-item-container {
      justify-content: space-between;
    }

    .form-item {
      label {
        padding-left: 0;
      }

      width: 390px;
    }

    .advanced-search-btn-group {
      display: flex;
      justify-content: flex-end;
      width: 100%;
      position: absolute;
      bottom: 0px;
      background: #fff;
      padding: 15px 20px;

      .base-button {
        margin: 0 10px;
      }
    }
  }

</style>
<style lang="scss" scoped>
.cover {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 99;
  background-color: rgba(0, 0, 0, 0.6);
}
</style>
